package com.liuqi.knet.rpc;

import java.io.Serializable;
import java.util.HashMap;
import java.util.Map;
import lombok.ToString;

/**
 * @author liuqi
 * @date 2025/3/6 15:16
 **/
@ToString
public class RpcInvocation implements Invocation, Serializable {

    private static final long serialVersionUID = -4335285085441097067L;

    private Object data;

    private Map<String, String> attachments;

    public RpcInvocation() {
    }

    public RpcInvocation(Object data) {
        this.data = data;
    }

    public RpcInvocation(Object data, Map<String, String> attachments) {
        this.data = data;
        this.attachments = attachments;
    }

    @Override
    public Object data() {
        return data;
    }

    @Override
    public Map<String, String> getAttachments() {
        return attachments;
    }

    @Override
    public String getAttachment(String key) {
        if (attachments != null) {
            return attachments.get(key);
        }
        return null;
    }

    @Override
    public String getAttachment(String key, String defaultValue) {
        if (attachments != null) {
            String val = attachments.get(key);
            return val == null ? defaultValue : val;
        }
        return defaultValue;
    }

    public void setAttachments(Map<String, String> attachments) {
        this.attachments = attachments == null ? new HashMap<String, String>() : attachments;
    }

    public void setAttachment(String key, String value) {
        if (attachments == null) {
            attachments = new HashMap<String, String>();
        }
        attachments.put(key, value);
    }

    public void setAttachmentIfAbsent(String key, String value) {
        if (attachments == null) {
            attachments = new HashMap<String, String>();
        }
        if (!attachments.containsKey(key)) {
            attachments.put(key, value);
        }
    }

    public void addAttachments(Map<String, String> attachments) {
        if (attachments == null) {
            return;
        }
        if (this.attachments == null) {
            this.attachments = new HashMap<String, String>();
        }
        this.attachments.putAll(attachments);
    }

    public void addAttachmentsIfAbsent(Map<String, String> attachments) {
        if (attachments == null) {
            return;
        }
        for (Map.Entry<String, String> entry : attachments.entrySet()) {
            setAttachmentIfAbsent(entry.getKey(), entry.getValue());
        }
    }

}
